package com.android.controler;



import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

import com.android.activity.R;
import com.android.activity.SenderActivity;

//public class RemoteControlSender extends Activity{
public class RemoteControlSender {
	private static final boolean DEBUG = true;
	private static final int REQUEST_ENABLE_BT = 3;
	private static final String TAG = "RCS.RCS";
	BluetoothAdapter mAdapter;
	Handler mHandler;
	int mConexion;
	   private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
	   BluetoothSocket mS;
	   OutputStream mOut;
	public static final int IDLE = 0;
	public static final int CONNECTING = 1;
	public static final int CONNECTED = 2;

	public RemoteControlSender(Object o, Handler h) {
		Log.d(TAG, "Constructor!!!!! ");
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		mHandler = h;
		setState(R.integer.RCS_IDLE);
	}

	private synchronized void setState(int state) {
		if (DEBUG)
			Log.d(TAG, "setState() " + mConexion + " -> " + state);
		mConexion = state;

		// Comunica el cambio de estado a la actividad.
		mHandler.obtainMessage(SenderActivity.ID_MSG, state, -1).sendToTarget();
	}

	public  void conecta(BluetoothDevice bt) {
		int estado=0;
		try {
			 mS = bt.createRfcommSocketToServiceRecord(MY_UUID);
			 estado = R.integer.RCS_CONNECTING;
			if (DEBUG)
				Log.d(TAG, "conecta - obten socket - OK");
		} catch (IOException e) {
			if (DEBUG)
				Log.d(TAG, "conecta - obten socket - ERROR");
			return;
		}
		try{
			mS.connect();
			estado = R.integer.RCS_CONNECTED;
			if (DEBUG)
				Log.d(TAG, "conecta - haz la conexion - OK");
		}
		catch(IOException e){
						if (DEBUG)
			Log.d(TAG, "conecta - haz la conexion - ERROR");
						return;
		}
		try {
            mOut =  mS.getOutputStream();
            estado = R.integer.RCS_OUTPUT_STREAM;
    		if (DEBUG)
				Log.d(TAG, "conecta - obten OutStream - OK"); 
		}
		catch (IOException e) {
			if (DEBUG)
				Log.d(TAG, "conecta - obten OutStream - ERROR"); 
			return;
		}
		setState(estado);
	}
//	public void write(int Command){
	public void write(byte[] Command){
		try {
			mOut.write(Command);
			if (DEBUG)
				Log.d(TAG, "write - Envia comando- OK");			
		} catch (Exception e) {
			if (DEBUG)
				Log.d(TAG, "write - Envia comando - ERROR");
		}
	}
}

